<template>
  <div class="container">
    <img src="@/assets/logo.png" alt="Logo" class="logo" />
    <form @submit.prevent="login" class="login-form-container">
      <input v-model="username" type="text" placeholder="用户名" required />
      <input v-model="password" type="password" placeholder="密码" required />
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/utils/request'; // 使用默认导入

const username = ref('');
const password = ref('');
const router = useRouter();
const route = useRoute();

async function login() {
  try {
    const response = await request.login({
      username: username.value,
      password: password.value
    });

    if (response?.access) {
      localStorage.setItem('token', response.access);
      localStorage.setItem('refreshToken', response.refresh);

      const redirect = route.query.redirect || '/welcome';
      router.push(redirect);
    }
  } catch (error) {
    console.error('登录失败:', error);

    // 使用可选链操作符防止 undefined 访问
    if (error?.response?.status === 401) {
      alert('认证失败，请重新登录');
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
      router.push('/login');
    } else if (error.request) {
      alert('无法连接到服务器，请检查网络连接');
    } else {
      alert('发生未知错误，请重试');
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #e6f7ff;
  padding: 20px;
}

.logo {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  align-self: center;
}

form {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  gap: 15px;
}

input {
  padding: 12px;
  font-size: 16px;
  border: 1px solid #b3d9ff;
  border-radius: 6px;
}

button {
  padding: 12px;
  font-size: 16px;
  background-color: #3a88c7;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #2b6fa6;
}
</style>